package cn.kow.kmall.core.response;

import java.util.HashMap;
import java.util.Map;

/**
 * 返回结果包装类
 * @Author: lijun
 * @Description:
 * @Date: Created in 2019-05-13 15:27
 * @Modified By:
 */
public class KmallResult<T> implements BaseResult {

    /**
     * 返回状态码
     */
    private Integer code;

    /**
     * 消息
     */
    private String msg;

    /**
     * 数据
     */
    private T data;

    private static final Integer SUCCESS_CODE = 200;

    private static final String SUCCESS_MSG = "success";

    private static final Integer FAIL_CODE = 400;

    private static final String FAIL_MSG = "fail";

    public static KmallResult build(Integer code, String msg) {
        return new KmallResult(code, msg);
    }

    public static <T> KmallResult build(Integer code, String msg, T data) {
        return new KmallResult(code, msg, data);
    }

    public static KmallResult build(BaseResultInfo result) {
        return new KmallResult(result.getCode(), result.getMessage());
    }

    public static KmallResult success() {
        return new KmallResult(SUCCESS_CODE, SUCCESS_MSG);
    }

    public static <T> KmallResult success(T data) {
        return new KmallResult(SUCCESS_CODE, SUCCESS_MSG, data);
    }

    public static KmallResult fail() {
        return new KmallResult(FAIL_CODE, FAIL_MSG);
    }

    public static KmallResult fail(String msg) {
        return new KmallResult(FAIL_CODE, msg);
    }

    public static Boolean isSuccess(KmallResult result) {
        return SUCCESS_CODE.equals(result.getCode());
    }

    public static Boolean isFail(KmallResult result) {
        return !isSuccess(result);
    }

    private KmallResult() {
    }

    private KmallResult(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
        this.data = null;
    }

    private KmallResult(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    @Override
    public String toString() {
        return "KmallResult{" +
                "code=" + code +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }

    public KmallResult put(String key, Object value) {
        Map<String, Object> map;
        if(this.data == null) {
            map = new HashMap<>();
            this.data = (T) map;
        } else {
            map = (Map<String, Object>) data;
        }
        map.put(key, value);
        return this;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}
